package com.jinyi.wwdeng.utils.dialog

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.bingoogolapple.baseadapter.BGAOnItemChildClickListener
import cn.bingoogolapple.baseadapter.BGARecyclerViewAdapter
import cn.bingoogolapple.baseadapter.BGAViewHolderHelper
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.DialogBindCardBinding
import com.jinyi.wwdeng.utils.recyclerview.GridSpacingItemDecoration
import org.json.JSONObject

/**
 * Author : wwdeng
 * Date : 2023/8/1 15:44
 * <p>
 * 每天进步一点点
 * <p>
 * Desc : 绑卡dialog
 */
class BindCardDialog: ProDialog {
    private lateinit var binding: DialogBindCardBinding
    private var mCallback: IDialogCallback? = null

    val dataList = arrayListOf(R.string.wave,R.string.orange,R.string.mtn,R.string.moov)
    var itemAdapter: ItemAdapter? = null

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width = App.getPhoneWidth()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(com.jinyi.pickerview.R.style.picker_view_slide_anim) //修改动画样式
        window!!.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = DialogBindCardBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initRecyclerView()
        showTypeDefaultView()
    }

    override fun initListener() {
        setOnClickListener(R.id.ivClose) //关闭
        setOnClickListener(R.id.btnAjouter)

        binding.editPhone.addTextChangedListener(ITextWatcher)
        binding.editPhoneComplete.addTextChangedListener(ITextWatcher)
    }

    override fun initData() {
        val bindList = arrayListOf<JSONObject>()
        for (i in 0 until dataList.size) {
            val tabObj = JSONObject()
            tabObj.put("id", i)
            tabObj.put("title", dataList[i])
            tabObj.put("isSelect", false)
            bindList.add(tabObj)
        }
        itemAdapter!!.data = bindList
    }

    override fun onViewClick(v: View?) {
        when(v!!.id){
            R.id.ivClose -> {//关闭
                dismiss()
            }
            R.id.btnAjouter -> {//提交
                val typeObj = getSelectTypeItem() ?: return
                if (getPhoneNumber() != getPhoneNumberComplete()){
                    return
                }
                if(mCallback != null){
                    mCallback!!.onSubmitParams(typeObj,getPhoneNumber())
                }
            }
        }
    }

    /**
     * 初始化类型列表
     */
    private fun initRecyclerView() {
        val layoutManager = GridLayoutManager(context,2)
        binding.recyclerView.layoutManager = layoutManager
        itemAdapter = ItemAdapter(binding.recyclerView)
        val leftDecoration = App.dp2px(10f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(2, leftDecoration,false))
        binding.recyclerView.adapter = itemAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        itemAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item
                for (i in 0..< itemAdapter!!.itemCount){
                    val item = itemAdapter!!.getItem(i)
                    if (i == position){
                        item.put("isSelect",true)
                    } else {
                        item.put("isSelect",false)
                    }
                }
                itemAdapter!!.notifyDataSetChanged()
            }
        })
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.editPhone.setBackgroundResource(R.drawable.base_circle_fill_f8f8f8)
        binding.editPhone.setTextColor(ContextCompat.getColor(context,R.color.color_0c092a))
        binding.editPhoneComplete.setBackgroundResource(R.drawable.base_circle_fill_f8f8f8)
        binding.editPhoneComplete.setTextColor(ContextCompat.getColor(context,R.color.color_0c092a))
        binding.errorTipsLayout.visibility = View.GONE
    }

    /**
     * 设置号码错误提示
     */
    fun showTypeErrorView(){
        binding.editPhone.setBackgroundResource(R.drawable.base_circle_frame_ff4d3e)
        binding.editPhone.setTextColor(ContextCompat.getColor(context,R.color.color_ff4d3e))
        binding.editPhoneComplete.setBackgroundResource(R.drawable.base_circle_frame_ff4d3e)
        binding.editPhoneComplete.setTextColor(ContextCompat.getColor(context,R.color.color_ff4d3e))
        binding.errorTipsLayout.visibility = View.VISIBLE
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        for (item in itemAdapter!!.data) {
            if (item.optBoolean("isSelect", false)){
                obj = item
                break
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun getPhoneNumber(): String{
        return binding.editPhone.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun getPhoneNumberComplete(): String{
        return binding.editPhoneComplete.text.toString()
    }

    class ItemAdapter(recyclerView: RecyclerView?) :
        BGARecyclerViewAdapter<JSONObject>(recyclerView, R.layout.item_bind_card_type) {
        override fun setItemChildListener(helper: BGAViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.itemLayout) //点击Item
        }
        override fun fillData(helper: BGAViewHolderHelper, position: Int, model: JSONObject) {
            val isSelect = model.optBoolean("isSelect", false)
            val itemLayout = helper.getView<RelativeLayout>(R.id.itemLayout)
            val ivImage = helper.getImageView(R.id.ivImage)
            val ivAvatar = helper.getImageView(R.id.ivAvatar)
            val tvTitle = helper.getTextView(R.id.tvTitle)
            tvTitle.text = mContext.getString(model.optInt("title"))

            if (isSelect) {
                itemLayout.setBackgroundResource(R.drawable.base_radius_fill_9fe76f_8)
                ivImage.setImageResource(R.mipmap.pic_bind_card_select_icon)
                tvTitle.setTextColor(ContextCompat.getColor(mContext,R.color.color_021e00))
            } else {
                itemLayout.setBackgroundResource(R.drawable.base_radius_fill_f8f8f8_8)
                ivImage.setImageResource(R.mipmap.pic_bind_card_normal_icon)
                tvTitle.setTextColor(ContextCompat.getColor(mContext,R.color.color_6e6e6e))
            }
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
        //确认
        fun onSubmitParams(typeObj: JSONObject,phoneNumber: String)
    }
}